<template>
  <div class="ma-content-block lg:flex justify-between p-4">
    <!-- CRUD 组件 -->
    <ma-crud :options="options" :columns="columns" ref="crudRef">
      <template #tableBeforeButtons="{ record }" >
        <a-button type="primary" @click="handlehuanqi">新增</a-button>
      </template>
      <template #operationCell="{ record }" >
        <a-link  @click="handleEdits(record)">编辑</a-link>
      </template>
      <template #contract_id="{record}">
        <div>{{ record.contract.name }}</div>
      </template>
      <template #ps_dept_id="{record}">
        <div>{{ record.dept?.name ||  '' }}</div>
      </template>
      <template #price_config="{record}">
        <a-popover >
          <a-link>查看详情</a-link>
          <template #content>
            <div >
              <div v-for="(item,index) in record.price_config" :key="index">
                <div v-if="item.transport_type == 1 && item.box[0].price !=''" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">集装箱：</div>
                  <div >
                    <div v-for="(items,indexs) in item.box" :key="indexs">{{ items.box_size == 1?'20英尺':'40英尺' }}：{{items.price}}元/{{handleunit(items.unit)}};</div> 
                  </div>
                </div>
                <div v-if="item.transport_type == 2 && item.price !=''" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">整车：</div>
                  <div>
                    <div >{{item.price}}元/{{handleunit(item.unit)}};</div> 
                  </div>
                </div>
                <div v-if="item.transport_type == 3 && item.price !=''" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">批量快运：</div>
                  <div>
                    <div >{{item.price}}元/{{handleunit(item.unit)}}； </div> 
                  </div>
                </div>
              </div>
            </div>
          </template>
        </a-popover>
        
      </template>
    </ma-crud>

    <!-- 新增 -->
    <a-modal :mask-closable="false"  v-model:visible="addShow" title="添加地址" :width="1000" ok-text='确认' :on-before-ok="handleBeforeAdd" >
      <div style="max-height:700px;" class="scrollable">
        <div class="flex" style="margin-bottom: 1.5%;">
          <div class="flex flex_1" style="margin-right: 24px;">
            <div style="width: 120px;">合同名称：</div>
            <a-input style="flex:1" placeholder="合同" v-model="info.name" disabled allow-clear />
          </div>
          <div class="flex flex_1" >
            <div style="width: 120px;">管辖区：</div>
            <a-select  v-model="fromData.guanxiaqu" style="flex:1"
              :options="guanxiaquList" :field-names="{ value: 'key', label: 'title' }" allow-clear allow-search
              placeholder="请选择管辖区"  />
          </div>
        </div>
        
        <div class="flex" style="margin-bottom: 1.5%;">
          <div class="flex flex_1" style="margin-right: 24px;">
            <div style="width: 120px;">送达地址：</div>
            <a-select  v-model="fromData.daodadi" style="flex:1"
              :options="daodadiList" :field-names="{ value: 'key', label: 'title' }" :filter-option="filterOption" allow-clear allow-search
              placeholder="请选择送达地址"  />
          </div>
          <div class="flex flex_1" >
            <div style="width: 120px;">收货人姓名：</div>
            <a-input style="flex:1" placeholder="收货人姓名" v-model="fromData.name" allow-clear />
          </div>
        </div>
        <div class="flex" style="margin-bottom: 1.5%;">
          <div class="flex flex_1" style="margin-right:24px;">
            <div style="width: 120px;">收货人电话：</div>
              <a-input style="flex:1" placeholder="收货人电话" v-model="fromData.mobile" allow-clear />
          </div>
          <div class="flex flex_1" >
            <div style="width: 120px;">收货人单位：</div>
            <a-input style="flex:1" placeholder="收货人单位" v-model="fromData.unit" allow-clear />
          </div>
        </div>
        <div class="flex" style="margin-bottom: 1.5%;">
          <div style="width: 120px;">详细地址：</div>
          <a-input style="flex:1" placeholder="详细地址" v-model="fromData.address" allow-clear />
        </div>
        <div class="flex" style="margin-bottom: 1.5%;">
          <div style="width: 120px;">配送地址：</div>
          <maps style="flex:1" v-if="addShow" @chuanzhi="handleChuanzhi" :fromData="fromData"></maps>
        </div>
        <div class="flex" >
          <div style="width: 120px;">计费配置：</div>
          <div style="padding-top: 20px;margin-left: 10px;">
            <div class=""  v-for="(items,indexs) in fromData.price_config" :key="indexs">
              <div class="flex align_center" style="margin-bottom: 2%;" v-if="items.transport_type == 2">
                  <div style="width: 80px;">整车：</div>
                  <div class="flex align_center">
                      <a-input v-model="items.price" style="width: 100px;" placeholder="金额" allow-clear  />
                      <div style="margin: 0 12px;"> 元/ </div>
                      <a-select v-model="items.unit" style="width: 100px;" placeholder="单位">
                          <a-option v-for="item of unitList" :value="item.id" :label="item.name"  />
                      </a-select>
                  </div>
              </div>
              <div class="flex " style="margin-bottom: 2%;" v-if="items.transport_type == 1">
                  <div style="width: 80px;">集装箱：</div>
                  <div class="flex align_end flex_1">
                      <div>
                          <div class="flex align_center" v-for="(item,index) in items.box" :key="index" style="margin-bottom: 2%;">
                              <div style="margin-right:12px;"> {{ item.box_size == 1?'20英尺':'40英尺' }} </div>
                              <a-input v-model="item.price" style="width: 100px;margin-left: 12px;" placeholder="金额" allow-clear  />
                              <div style="margin: 0 12px;"> 元/ </div>
                              <a-select v-model="item.unit" style="width: 100px;" placeholder="单位">
                                  <a-option v-for="items of unitList" :value="items.id" :label="items.name"  />
                              </a-select>
                          </div>
                      </div>
                  </div>
              </div>
              <div class="flex align_center" v-if="items.transport_type == 3">
                  <div style="width: 80px;">批量快运：</div>
                  <div class="flex align_center">
                      <a-input v-model="items.price" style="width: 100px;" placeholder="金额" allow-clear  />
                      <div style="margin: 0 12px;"> 元/ </div>
                      <a-select v-model="items.unit" style="width: 100px;" placeholder="单位">
                          <a-option v-for="item of unitList" :value="item.id" :label="item.name"  />
                      </a-select>
                  </div>
              </div>
            </div>
          </div>
          
        </div>
      </div>
    </a-modal>
    <!-- 编辑 -->
    <a-modal :mask-closable="false"  v-model:visible="editShow" title="编辑地址" :width="1000" ok-text='确认' :on-before-ok="handleBeforeEdit"  >
      <div style="max-height:700px;" class="scrollable">
        <div class="flex" style="margin-bottom: 1.5%;">
          <div style="width: 120px;">合同名称：</div>
          <a-input style="flex:1" placeholder="合同" v-model="info.name" disabled allow-clear />
        </div>
        <div class="flex" style="margin-bottom: 1.5%;">
          <div style="width: 120px;">管辖区：</div>
          <a-select  v-model="fromData.guanxiaqu" style="flex:1"
            :options="guanxiaquList" :field-names="{ value: 'key', label: 'title' }" allow-clear allow-search
            placeholder="请选择管辖区"  />
        </div>
        <div class="flex" style="margin-bottom: 1.5%;">
          <div style="width: 120px;">送达地址：</div>
          <a-select  v-model="fromData.daodadi" style="flex:1"
            :options="daodadiList" :field-names="{ value: 'key', label: 'title' }" :filter-option="filterOption" allow-clear allow-search
            placeholder="请选择送达地址"  />
        </div>
        <div class="flex" style="margin-bottom: 1.5%;">
          <div style="width: 120px;">收货人姓名：</div>
          <a-input style="flex:1" placeholder="收货人姓名" v-model="fromData.name" allow-clear />
        </div>
        <div class="flex" style="margin-bottom: 1.5%;">
          <div style="width: 120px;">收货人电话：</div>
          <a-input style="flex:1" placeholder="收货人电话" v-model="fromData.mobile" allow-clear />
        </div>
        <div class="flex" style="margin-bottom: 1.5%;">
          <div style="width: 120px;">收货人单位：</div>
          <a-input style="flex:1" placeholder="收货人单位" v-model="fromData.unit" allow-clear />
        </div>
        <div class="flex" style="margin-bottom: 1.5%;">
          <div style="width: 120px;">详细地址：</div>
          <a-input style="flex:1" placeholder="详细地址" v-model="fromData.address" allow-clear />
        </div>
        <div class="flex" style="margin-bottom: 1.5%;">
          <div style="width: 120px;">配送地址：</div>
          <maps style="flex:1" v-if="editShow" @chuanzhi="handleChuanzhi" :fromData="fromData"></maps>
        </div>
        <div class="flex" >
          <div style="width: 120px;">计费配置：</div>
          <div style="padding-top: 20px;margin-left: 10px;">
            <div class=""  v-for="(items,indexs) in fromData.price_config" :key="indexs">
              <div class="flex align_center" style="margin-bottom: 2%;" v-if="items.transport_type == 2">
                  <div style="width: 80px;">整车：</div>
                  <div class="flex align_center">
                      <a-input v-model="items.price" style="width: 100px;" placeholder="金额" allow-clear  />
                      <div style="margin: 0 12px;"> 元/ </div>
                      <a-select v-model="items.unit" style="width: 100px;" placeholder="单位">
                          <a-option v-for="item of zhengcheUnitList" :value="item.id" :label="item.name"  />
                      </a-select>
                  </div>
              </div>
              <div class="flex " style="margin-bottom: 2%;" v-if="items.transport_type == 1">
                  <div style="width: 80px;">集装箱：</div>
                  <div class="flex align_end flex_1">
                      <div>
                          <div class="flex align_center" v-for="(item,index) in items.box" :key="index" style="margin-bottom: 2%;">
                              <div style="margin-right:12px;"> {{ item.box_size == 1?'20英尺':'40英尺' }} </div>
                              <a-input v-model="item.price" style="width: 100px;margin-left: 12px;" placeholder="金额" allow-clear  />
                              <div style="margin: 0 12px;"> 元/ </div>
                              <a-select v-model="item.unit" style="width: 100px;" placeholder="单位">
                                  <a-option v-for="items of unitList" :value="items.id" :label="items.name"  />
                              </a-select>
                          </div>
                      </div>
                  </div>
              </div>
              <div class="flex align_center" v-if="items.transport_type == 3">
                  <div style="width: 80px;">批量快运：</div>
                  <div class="flex align_center">
                      <a-input v-model="items.price" style="width: 100px;" placeholder="金额" allow-clear  />
                      <div style="margin: 0 12px;"> 元/ </div>
                      <a-select v-model="items.unit" style="width: 100px;" placeholder="单位">
                          <a-option v-for="item of zhengcheUnitList" :value="item.id" :label="item.name"  />
                      </a-select>
                  </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script setup>
import { ref, reactive,onMounted } from 'vue'
import systemUserContractAddress from '@/api/system/systemUserContractAddress'
import maps from "@/views/prediction/map/index.vue";
import { Message } from '@arco-design/web-vue'
import { pinyin } from "pinyin-pro"
import tool from '@/utils/tool'
import commonApi from "@/api/common";
import * as common from '@/utils/common'
import { request } from "@/utils/request.js";
const crudRef = ref()
const info = ref({})
const addShow = ref(false)
const editShow = ref(false)
const fromData = ref({})
const dept_list = ref([])
const unitList = ref([])
const zhengcheUnitList = ref([
        {id: 1,name: "吨"},
        {id: 2,name: "车"},
        {id: 5,name: "吨/天"},
        {id: 6,name: "车/天"},
        {id: 8,name: "车/小时"},
        {id: 9,name: "天"},
        {id: 10,name: "小时"},
    ])
const guanxiaquList = ref([])
const daodadiList = ref([])

const filterOption = (v,option)=>{
        return option.keywords.some(keywords=>keywords.includes(v))
    }

onMounted(()=>{
  
})

const open = (row)=>{
  info.value = row
  fromData.value = {
    contract_id:row.id,
    name:'',
    mobile:'',
    guanxiaqu:'',
    daodadi:'',
    unit:'',
    area:'',
    city:'',
    province:'',
    address:'',
    deliveryAddress:'',
    lat:'',
    lng:'',
    price_config:[
      {
        transport_type: "2",
        price:'',  // 金额
        unit:'',   // 单位
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
        is_jieti:0,
      },
      {
        transport_type: "1",
        is_jieti:0,
        box: [
          {
            box_size: 1,
            price: '',
            unit: ""
          },
          {
            box_size: 2,
            price: '',
            unit: ""
          }
        ],
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
      },
      {
        transport_type: "3",
        price:'',  // 金额
        unit:'',   // 单位
        is_jieti:0,
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
      },
    ],
    // ps_dept_id:'',
  }
  crudRef.value.requestData()
  handleDeptList()
  commonApi.getDict("guanxiaqu").then((res) => {
    let _data = res.data;
    guanxiaquList.value = _data
  });
  commonApi.getDict("daodadi").then((res) => {
    let _data = res.data;
    _data.map((v,i)=>{
      v.keywords = [
          v.title,
          pinyin(v.title,{toneType:'none',pattern:'first'}).split(' ').join(''),
          pinyin(v.title,{toneType:'none',pattern:'first'}).split(' ').join('').toUpperCase()
        ]
    })
    console.log(_data)
    daodadiList.value = _data
  });
  request({
      url:'financial/unit/index',
      method: 'get',
      params:{
        openPage:false
      },
    }).then(res=>{
      unitList.value = res.data.items
    })
}
const handleunit = (item)=>{
  let name = ''
  unitList.value.map((v,i)=>{
    if(v.id == item){
      name = v.name
    }
  })
  return name
}
const handleDeptList = () => {   //  获取公司列表
    request({
        url: 'system/dept/remote',
        method: 'post',
        data: {
        openPage: false,
        remoteOption: {
            filter: {
            type: ['=', 3],
            status: ['=',1]
            },
            select: ["id", "name"],
            sort: { id: "desc" }
        }
        }
    }).then(res => {
        dept_list.value = res.data
    })
}
const handleBeforeEdit = async ()=>{
  if(fromData.value.guanxiaqu == ''){
    Message.error('请选择管辖区')
    return false
  }else if(fromData.value.daodadi == ''){
    Message.error('请输入到达地')
    return false
  }else if(fromData.value.mobile == ''){
    Message.error('请输入收货人电话')
    return false
  }else if(fromData.value.address == ''){
    Message.error('请输入详细地址')
    return false
  }else{
    let res = await systemUserContractAddress.update(fromData.value.address_id,fromData.value)
    console.log(res)
    if(res.code == 200){
      Message.success('编辑成功')
      crudRef.value.refresh()
      return true
    }else{
      Message.success(res.message)
      return false
    }
    
  }
}
// const handleEdit = () =>{
  
  
// }
const handleEdits = (row) =>{
  fromData.value = {
    contract_id:row.contract_id,
    name:row.name,
    guanxiaqu:row.guanxiaqu + '',
    daodadi:row.daodadi + '',
    mobile:row.mobile,
    unit:row.unit,
    area:row.area,
    city:row.city,
    province:row.province,
    address:row.address,
    deliveryAddress:row.deliveryAddress,
    lat:row.lat,
    lng:row.lng,
    price_config:row.price_config,
    // ps_dept_id:row.ps_dept_id,
    address_id:row.id
  }
  editShow.value = true
  
}
const handleBeforeAdd = async ()=>{
  if(fromData.value.guanxiaqu == ''){
    Message.error('请选择管辖区')
    return false
  }else if(fromData.value.daodadi == ''){
    Message.error('请选择到达地址')
    return false
  }else if(fromData.value.mobile == ''){
    Message.error('请输入收货人电话')
    return false
  }else if(fromData.value.address == ''){
    Message.error('请输入详细地址')
    return false
  }else{
    let res = await systemUserContractAddress.save(fromData.value)
    if(res.code == 200){
      Message.success('添加成功')
      crudRef.value.refresh()
      return true
    }else{
      Message.success(res.message)
      return false
    }
  }
}
const handlehuanqi = ()=>{
  addShow.value = true
  fromData.value = {
    contract_id:info.value.id,
    name:'',
    guanxiaqu:'',
    daodadi:'',
    mobile:'',
    unit:'',
    area:'',
    city:'',
    province:'',
    address:'',
    deliveryAddress:"",
    lat:'',
    lng:'',
    price_config:[
      {
        transport_type: "2",
        price:'',  // 金额
        unit:'',   // 单位
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
        is_jieti:0,
      },
      {
        transport_type: "1",
        is_jieti:0,
        box: [
          {
            box_size: 1,
            price: '',
            unit: ""
          },
          {
            box_size: 2,
            price: '',
            unit: ""
          }
        ],
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
      },
      {
        transport_type: "3",
        price:'',  // 金额
        unit:'',   // 单位
        is_jieti:0,
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
      },
    ],
    // ps_dept_id:'',
  }
}

const handleChuanzhi = (row)=>{
  console.log(row)
  fromData.value.area = row.adname
  fromData.value.city = row.cityname
  fromData.value.province = row.pname
  fromData.value.deliveryAddress = row.deliveryAddress
  fromData.value.lat = row.location.lat
  fromData.value.lng = row.location.lng
}
const options = reactive({
  id: 'flyos_system_user_contract_address',
  rowSelection: {
    showCheckedAll: true
  },
  pk: 'id',
  operationColumn: true,
  operationWidth: 160,
  autoRequest:false,
  formOption: {
    viewType: 'modal',
    width: 600
  },
  api: systemUserContractAddress.getList,
  recycleApi: systemUserContractAddress.getRecycleList,
  add: {
    show: false,
    api: systemUserContractAddress.save,
    auth: ['system:userContractAddress:save']
  },
  edit: {
    show: false,
    api: systemUserContractAddress.update,
    auth: ['system:userContractAddress:update']
  },
  delete: {
    show: true,
    api: systemUserContractAddress.deletes,
    auth: ['system:userContractAddress:delete'],
    realApi: systemUserContractAddress.realDeletes,
    realAuth: ['system:userContractAddress:realDeletes']
  },
  recovery: {
    show: false,
    api: systemUserContractAddress.recoverys,
    auth: ['system:userContractAddress:recovery']
  },
  import: {
    show: false,
    url: 'system/userContractAddress/import',
    templateUrl: 'system/userContractAddress/downloadTemplate',
    auth: ['system:userContractAddress:import']
  },
  export: {
    show: false,
    url: 'system/userContractAddress/export',
    auth: ['system:userContractAddress:export']
  },
  beforeRequest:(params)=>{
    params.contract_id = info.value.id
  }
})

const columns = reactive([
  {
    title: "",
    dataIndex: "id",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    commonRules: {
      required: true,
      message: "请输入"
    }
  },
  
  {
    title: "详细地址",
    dataIndex: "address",
    formType: "input",
    search: true
  },
  {
    title: "配送地址",
    dataIndex: "deliveryAddress",
    formType: "input",
    search: true
  },
  // {
  //   title: "配送公司",
  //   dataIndex: "ps_dept_id",
  //   formType: "input",
  // },
  
  {
    title: "计费规则",
    dataIndex: "price_config",
    formType: "input",
    search: true
  },
  {
    title: "合同名称",
    dataIndex: "contract_id",
    formType: "select",
    hide: true,
    addDisplay: false,
    editDisplay: false,
  },
  {
    title: "收货人姓名",
    dataIndex: "name",
    formType: "input",
    search: true
  },
  {
    title: "收货人电话",
    dataIndex: "mobile",
    formType: "input",
    search: true
  },
  {
    title: "收货人单位",
    dataIndex: "unit",
    formType: "input",
    search: true
  },
  // {
  //   title: "区域",
  //   dataIndex: "area",
  //   formType: "input",
  //   search: true
  // },
  // {
  //   title: "城市",
  //   dataIndex: "city",
  //   formType: "input",
  //   search: true
  // },
  // {
  //   title: "省会",
  //   dataIndex: "province",
  //   formType: "input",
  //   search: true
  // },
  
  // {
  //   title: "纬度",
  //   dataIndex: "lat",
  //   formType: "input",
  // },
  // {
  //   title: "经度",
  //   dataIndex: "lng",
  //   formType: "input",
  // },
  
  {
    title: "创建时间",
    dataIndex: "created_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "更新时间",
    dataIndex: "updated_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "删除时间",
    dataIndex: "deleted_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "创建者",
    dataIndex: "created_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "更新者",
    dataIndex: "updated_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  }
])

defineExpose({ open });
</script>

<style lang="less" scoped>
  .scrollable {
    overflow: auto;
    -ms-overflow-style: none;
  }
  .scrollable::-webkit-scrollbar {
    display: none;
  }
</style>

<script> export default { name: 'system:userContractAddress' } </script>